package com.spring.future.common.config;

import com.spring.future.common.utils.Const;
import com.spring.future.common.utils.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.util.HtmlUtils;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * Created by liuj on 2016-08-19.
 */
@ControllerAdvice
public class MyWebBindingInitializer {

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : HtmlUtils.htmlEscape(text));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? Objects.toString(value) : "";
            }
        });

        // LocalDateTime 类型转换
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                if(StringUtils.isNotBlank(text)) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Const.FORMATTER_DATE_TIME);
                    LocalDateTime localDateTime = LocalDateTime.parse(text,formatter);
                    setValue(localDateTime);
                }
            }
        });


        // LocalDate 类型转换
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                if(StringUtils.isNotBlank(text)) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Const.FORMATTER_DATE);
                    setValue(LocalDate.parse(text,formatter));
                }
            }
        });

        // LocalTime 类型转换
        binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                if(StringUtils.isNotBlank(text)) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Const.FORMATTER_TIME);
                    setValue(LocalTime.parse(text,formatter));
                }
            }
        });
    }
}
